﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.IO;
using System.Threading;

namespace GGSharp.Radio.XML
{
    public class ChannelList : List<Channel>
    {
        protected delegate void ReadDelegateText(TextReader reader);
        protected delegate void ReadDelegateUri(string uri);

        public event EventHandler Loaded;

        private string _version;
        private Channel _defaultChannel;

        private object _syncRoot = new object();

        public Channel DefaultChannel
        {
            get { return _defaultChannel; }
            protected set { _defaultChannel = value; }
        }

        public string Version
        {
            get { return _version; }
            protected set { _version = value; }
        }

        public IAsyncResult BeginRead(TextReader reader, AsyncCallback callback, object @object)
        {
            return new ReadDelegateText(Read).BeginInvoke(reader, callback, @object);
        }

        public IAsyncResult BeginRead(string uri, AsyncCallback callback, object @object)
        {
            return new ReadDelegateUri(Read).BeginInvoke(uri, callback, @object);
        }

        public void Read(TextReader reader)
        {
            Read(XmlReader.Create(reader));
        }

        public void Read(string uri)
        {
            Read(XmlReader.Create(uri));
        }

        protected void Read(XmlReader reader)
        {
            lock (_syncRoot)
            {
                this.Clear();
                _defaultChannel = null;
                _version = null;

                while (reader.Read())
                {
                    if (reader.NodeType == XmlNodeType.Element)
                    {
                        switch (reader.Name)
                        {
                            case "channel":
                                Channel channel = new Channel(reader);
                                this.Add(channel);
                                break;
                            case "default":
                                DefaultChannel = new Channel(reader);
                                break;
                            case "version":
                                Version = reader.Value;
                                break;
                        }
                    }
                }
            }

            if (Loaded != null)
                Loaded(this, EventArgs.Empty);
        }
    }
}
